var util = require('../../utils/util.js');
var ajax = require('../../utils/ajax.js');
var app = getApp();

Page({
    data: {
        dataLoaded: false,

        lng: '',
        lat: '',
        animationData: {},

        markers: [],
        polyline: [],
        controls: [],
        isOpen: false,
        isShow: false,
        money: ''
    },
    onShareAppMessage: function() {
        return {
            title: app.config.shareTitle,
            path: "/pages/index/index"
        }
    },

    onLoad(options) {
        var _self = this;

        app.getUserInfo(function(userInfo) {
            _self.userInfo = userInfo;
            util.jumpByScene(options.scene);
            _self._quietLogin();
        });

        wx.getSystemInfo({
            success: function(res) {
                var winWid = res.windowWidth;
                var winHei = res.windowHeight;

                _self.setData({
                    controls: [{
                        id: 1,
                        iconPath: '/imgs/scan.png',
                        position: {
                            left: (winWid - 100) / 2,
                            top: winHei - 100,
                            width: 100,
                            height: 36
                        },
                        clickable: true
                    }, {
                        id: 2,
                        iconPath: '/imgs/shop_icon.png',
                        position: {
                            left: winWid - 57,
                            top: winHei - 109,
                            width: 47,
                            height: 47
                        },
                        clickable: true
                    }]
                });
            }
        });
    },

    //扫一扫
    _scan() {
        wx.scanCode({
            success: (res) => {
                var path = res.path;

                if (path) {
                    wx.redirectTo({
                        url: path
                    });
                } else {
                    wx.showModal({
                        title: '系统提示',
                        content: '仅支持共享消费链商户二维码',
                        showCancel: false
                    })
                }
            }
        });
    },
    //跳转到商户端后台登录界面
    _goToBackstage: function() {
        if (app.getShopSid()) {
            wx.navigateTo({
                url: '/pages/backstage/backstage'
            })
        } else {
            wx.navigateTo({
                url: '/pages/backstageLogin/backstageLogin'
            })
        }
    },
    //地图事件管理
    _controltap(e) {
        if (e.controlId == 1) {
            this._scan();
        } else if (e.controlId == 2) {
            this._goToBackstage();
        }

    },
    //地图图标
    _markertap(obj) {
        var curShop;

        (this.shopList || []).some(function(shop) {
            if (shop.shopid == obj.markerId) {
                curShop = shop;
                return true;
            }
        });
        if (!curShop) {
            return;
        }
        ajax.G('/openapi/User/getLocation', {
            addr: curShop.address
        }, function(data) {
            var addressInfo = JSON.parse(data.result)['result'];

            wx.openLocation({
                latitude: addressInfo.location.lat,
                longitude: addressInfo.location.lng,
                name: curShop.shopname,
                address: curShop.address,
            })
        })
    },

    /**
     * 获取gps定位
     */
    _getLocation() {
        var _self = this;

        app.getLocation(function(location) {
            var {
                lat,
                lng
            } = location;

            _self.setData({
                lat,
                lng
            });
            _self._getNearShop(location);
        })
    },

    /**
     * 重新授权共享地址
     */
    _getGPS: function() {
        var _self = this;

        wx.openSetting({
            success: function(res) {
                _self._getLoaction();
            }
        })
    },

    /**
     * 获取最近的店
     */
    _getNearShop: function(location) {
        var _self = this;
        var {
            lat,
            lng
        } = location;

        ajax.P('/openapi/User/getNearbyShop', {
            page: 1,
            lng,
            lat,
        }, function(data) {
            var shopList = data.result['shopInfo'] || [];
            var markers = [];

            _self.shopList = shopList;

            shopList.forEach(function(shop) {
                markers.push({
                    id: shop.shopid,
                    latitude: shop.lat,
                    longitude: shop.lng,
                    // title: shop.shopname,
                    iconPath: "/imgs/dian.png",
                    width: 45,
                    height: 45,
                });
            });
            _self.setData({
                markers,
                dataLoaded: true,
            });

        });
    },

    /**
     * openid静默登陆
     */
    _quietLogin: function() {
        var $this = this;

        wx.login({
            success: function(res) {
                ajax.G(
                    '/openapi/User/getUserOpenID', {
                        jscode: res.code
                    },
                    function(d) {
                        app.setOpenId(d.result.openid);
                        $this._openIdLogin(d.result.openid, function() {
                            $this._getLuckBagList();
                        });
                    }
                );
            },
            fail: function() {},
            complete: function() {}
        })
    },

    /**
     * openid静默登陆
     */
    _openIdLogin: function(openid, cb) {
        var $this = this;
        ajax.P(
            '/openapi/User/login', {
                openId: openid,
                nickName: $this.userInfo.nickName,
                avatarUrl: $this.userInfo.avatarUrl
            },
            function(d) {
                var userSid = d.result.userSid;
                if (userSid) {
                    app.setUserSid(userSid);
                    $this._getLocation();
                    cb && cb();
                }
            }
        );
    },
    /**
     * 拆红包的动画效果、数据请求
     */
    _animation: function() {
        var _self = this;
        var isShaking = true;
        var animation = wx.createAnimation({
            transformOrigin: "50% 50%",
            duration: 30,
            timingFunction: "linear",
            delay: 0
        })

        if (!this.data.isOpen) {
            wx.vibrateShort();
            var shaking = setInterval(function() {

                if (isShaking) {
                    animation.translate(5, 5).step();
                } else {
                    animation.translate(-5, -5).step();
                }

                isShaking = !isShaking;

                this.setData({
                    animationData: animation.export()
                })
            }.bind(this), 30)
            setTimeout(function() {
                clearInterval(shaking);
                animation.translate(0, 0).step();
                this.setData({
                    animationData: animation.export()
                })
                this._getLuckBag();
            }.bind(this), 1000)
        }
    },
    /**
     * 获取店铺红包列表
     */
    _getLuckBagList: function() {
        var url = "/openapi/User/hongbaoList";
        var _self = this;
        ajax.P(url, {}, function(data) {
            _self._luckBagList = data.result.list;
            if (_self._luckBagList.length != 0) {
                _self.setData({
                    isShow: true
                })
            }
        })
    },
    /**
     * 获取店铺红包
     */
    _getLuckBag: function() {
        var _self = this;
        var url = "/openapi/User/userGetHongBao";
        var hongbaoId = this._luckBagList.length > 0 ? this._luckBagList[0].hongbao_id : '';
        var paramsData = {
            hongbaoId
        }
        ajax.P(url, paramsData, function(data) {
            _self.setData({
                money: data.result.money,
                isOpen: true
            })
        })
    },
    /**
     * 关闭红包
     */
    _closed: function() {
        this.setData({
            isShow: false
        })
    },
    /**
     * 跳转到个人中心
     */
    _jump: function(evt) {
        var url = evt.currentTarget.dataset.url;
        this.setData({
            isShow: false
        })
        wx.switchTab({
            url
        })

    }
});